package activities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.MyLocationOverlay;
import com.searchparking.R;
import com.searchparking.BUS.DataSingleton;
import com.searchparking.BUS.ParseJsonData;
import com.searchparking.DTO.InfoObject;

public class MapViewResult extends FragmentActivity implements LocationListener {

	GoogleMap googleMap;
	private ArrayList<InfoObject> aParking;
	String current_address, position_address;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		aParking = new ArrayList<InfoObject>();
		setContentView(R.layout.activity_map_view_result);
		// Getting Google Play availability status
		Intent i = new Intent();
		int distance = i.getIntExtra("distance", 0);
		Double latitude = i.getDoubleExtra("latitude", 0);
		Double longitude = i.getDoubleExtra("longitude", 0);
		// Log.d("");
		int status = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(getApplicationContext());

		// Showing status
		if (status != ConnectionResult.SUCCESS) { // Google Play Services are
													// not available

			int requestCode = 10;
			Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
					requestCode);
			dialog.show();

		} else { // Google Play Services are available

			// Getting reference to the SupportMapFragment of activity_main.xml
			SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map_search_result);

			// Getting GoogleMap object from the fragment
			googleMap = fm.getMap();

			// // Enabling MyLocation Layer of Google Map
			googleMap.setMyLocationEnabled(true);

			// Getting LocationManager object from System Service
			// LOCATION_SERVICE
			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

			// Creating a criteria object to retrieve provider
			Criteria criteria = new Criteria();

			// Getting the name of the best provider
			String provider = locationManager.getBestProvider(criteria, true);

			// Getting Current Location
			Location location = locationManager.getLastKnownLocation(provider);

			if (location != null) {
				onLocationChanged(location);
			}
			locationManager.requestLocationUpdates(provider, 20000, 0, this);
			// Tạo đối tương parsrjsononfo
			JSONObject data = DataSingleton.data;
			ParseJsonData parseJon = new ParseJsonData();
			try {
				parseJon.parseData(data);
				LatLng current = new LatLng(latitude, longitude);
				aParking = parseJon.getListFromCurrent(
						Double.parseDouble(String.valueOf(distance)), current);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d("MAPRESUKT", String.valueOf(aParking.size()));
			addMarkertoMap(aParking, googleMap);

		}
		// Marker click listener
		googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker marker) {

				String position_address = marker.getTitle();
				Double des_latitude = marker.getPosition().latitude;
				Double des_longitude = marker.getPosition().longitude;
				
				Toast.makeText(getApplicationContext(), position_address,
						100000).show();
				Bundle bundle = new Bundle();
				bundle.putString("CurrentAddress", current_address);
				bundle.putString("PositionAddress", position_address);
				bundle.putDouble("DesLatitude", des_latitude);
				bundle.putDouble("DesLongitude", des_longitude);
				

				Intent intent = new Intent(MapViewResult.this,
						SearchDirection.class);

				intent.putExtras(bundle);

				startActivity(intent);
				return false;

			}
		});
	}

	@Override
	public void onLocationChanged(Location location) {

		// Getting latitude of the current location
		double latitude = location.getLatitude();

		// Getting longitude of the current location
		double longitude = location.getLongitude();
		LatLng latLng = new LatLng(latitude, longitude);

		// Showing the current location in Google Map
		googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

		// Zoom in the Google Map
		googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	}

	private void addMarkertoMap(ArrayList<InfoObject> arrayLoc,
			GoogleMap mapGoogle) {

		for (int i = 0; i < arrayLoc.size(); i++) {
			Double lat = Double.parseDouble(arrayLoc.get(i).getLati());
			Double longi = Double.parseDouble(arrayLoc.get(i).getLongi());

			LatLng MarkerPos = new LatLng(lat, longi);
			Marker markerCustom = mapGoogle.addMarker(new MarkerOptions()
					.position(MarkerPos).title(arrayLoc.get(i).getAddr()));
		}
	}

}
